import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // baseURL: 'http://ihrm-java.itheima.net', // url = base url + request url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  // 携带token
  const token = store.state.user.token
  if (token) {
    // 对象新增属性 两种方式 点或者中括号
    config.headers['Authorization'] = `Bearer ${token}`
  }
  return config
},
error => {
  console.log(error) // for debug
  return Promise.reject(error)
}
)

// response interceptor
service.interceptors.response.use(response => {
  // 请求成功
  if (response.data.success) {
    return response.data
  } else {
    // 请求未成功
    // 提示
    Message({
      message: response.data.message,
      type: 'error'
    })
    // 抛出错误
    return Promise.reject(new Error(response.data.message))
  }
},
error => {
  // console.dir(error)
  // 当response中data.code响应码为10002时 就表示token失效 删除token及用户信息 跳转至登录页
  if (error.response && error.response.data && error.response.data.code === 10002) {
    store.dispatch('user/userLogout')
    // 跳转至登录
    router.push('/login')
    return Message({
      message: '登录超时,请重新登录',
      type: 'error'
    })
  }
  return Promise.reject(error)
}
)

export default service
